﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GLY_XieTong;
using fuzhu;
using System.Data.SqlClient;

namespace SML_XieTong
{
    public class SMLXieTong
    {
        /// <summary>
        /// 视美乐业务同步
        /// </summary>
        /// <param name="CLX">同步类型</param>
        /// <param name="IID">同步id，如果是0，就全部同步</param>
        /// <param name="CCONSTR">中间库连接字符串</param>
        /// <returns></returns>
        public string HANDSMLXieTong(string CLX, int IID, string CCONSTR)
        {
            string cErr = "";
            string sqlpo = "";
            DataTable dtSource = new DataTable();
            DataTable dtInter = new DataTable();
            XieTong XT = new XieTong(CCONSTR);
            TongBu tongBu = new TongBu(CCONSTR,1);
            switch (CLX)
            {
                case "存货档案同步":
                    cErr += "存货分类："+ tongBu.INSDangAn("存货分类");
                    cErr += "计量单位组：" + tongBu.INSDangAn("计量单位组");
                    cErr += "计量单位：" + tongBu.INSDangAn("计量单位");
                    cErr += "存货档案：" + tongBu.INSDangAn("存货档案");
                    cErr += "存货档案SUB：" + tongBu.INSDangAn("存货档案SUB");
                    cErr += "存货档案BAS：" + tongBu.INSDangAn("存货档案BAS");
                    //cErr += "存货分类INS中间表："+ XT.DangAnINSZJB("存货分类INS中间表",XT.cConStrB) + "\r\n";
                    //cErr += "计量单位组INS中间表："+ XT.DangAnINSZJB("计量单位组INS中间表", XT.cConStrB) +"\r\n";
                    //cErr += "计量单位INS中间表："+ XT.DangAnINSZJB("计量单位INS中间表", XT.cConStrB) + "\r\n"; ;
                    //cErr += "存货档案INS中间表："+ XT.DangAnINSZJB("存货档案INS中间表", XT.cConStrB) + "\r\n"; ;
                    ////XT.DangAnINSZJB("存货档案SUBINS中间表");
                    ////XT.DangAnINSZJB("存货档案BASINS中间表");

                    //cErr += "中间表TO存货分类："+ XT.ZJBINSDangAn("中间表TO存货分类", XT.cConStrA) + "\r\n"; ;
                    //cErr += "中间表TO计量单位组："+ XT.ZJBINSDangAn("中间表TO计量单位组", XT.cConStrA) + "\r\n"; ;
                    //cErr += "中间表TO计量单位："+ XT.ZJBINSDangAn("中间表TO计量单位", XT.cConStrA) + "\r\n"; ;
                    //cErr += "中间表TO存货档案："+ XT.ZJBINSDangAn("中间表TO存货档案", XT.cConStrA) + "\r\n"; ;

                    break;
                case "客户档案同步":
                    cErr += "客户分类：" + tongBu.INSDangAn("客户分类");
                    cErr += "客户档案：" + tongBu.INSDangAn("客户档案");
                    cErr += "客户银行：" + tongBu.INSDangAn("客户银行");
                    cErr += "客户地址：" + tongBu.INSDangAn("客户地址");
                    //cErr = "客户分类INS中间表："+ XT.DangAnINSZJB("客户分类INS中间表", XT.cConStrB) + "\r\n"; ;
                    //cErr += "客户档案INS中间表："+ XT.DangAnINSZJB("客户档案INS中间表", XT.cConStrB) + "\r\n"; ;
                    ////XT.DangAnINSZJB("客户银行INS中间表");
                    ////XT.DangAnINSZJB("客户地址INS中间表");
                    //cErr += "中间表TO客户分类："+ XT.ZJBINSDangAn("中间表TO客户分类", XT.cConStrA) + "\r\n"; ;
                    //cErr += "中间表TO客户档案："+ XT.ZJBINSDangAn("中间表TO客户档案", XT.cConStrA) + "\r\n"; ;

                    break;
                case "数字采购订单转激光销售订单":
                    #region  A采购订单到B销售订单
                    //查询单据然后批量进行更新
                    cErr = "";

                    sqlpo = string.Format(@"SELECT  a.POID, a.ufts,a.cpoid FROM po_pomain a,dbo.PO_Pomain_extradefine b WHERE a.POId= b.poid 
and a.cvencode='{0}' and isnull(a.cVerifier,'')<>'' 
",  XT.GetcVenCode());

                    //有id的取id，没id的取最近一个月的
                    if (IID != 0)
                    {
                        sqlpo += string.Format(" and a.poid= {0}", IID);
                    }
                    else
                    {
                        sqlpo += String.Format(" and isnull({0},'')=''  and a.dpodate>'2021-9-8' and a.dpodate>DATEADD(MONTH,-1,getdate())", XT.cTargetCodeColA);
                    }


                    DataTable dtPO = DbHelper2.Execute(sqlpo, XT.cConStrA).Tables[0];
                    for (int k = 0; k < dtPO.Rows.Count; k++)
                    {
                        int iPoid = DbHelper.GetDbInt(dtPO.Rows[k]["POID"]);
                        string cPoid = DbHelper.GetDbString(dtPO.Rows[k]["cpoid"]);
                        //检查中间表有没有未同步的,去掉检查已完成的，生成的时候检查
                        sqlpo = string.Format(@"select count(0) from zdy_inter_somain where (cstatus ='0') and poid = '{0}'  ", iPoid);
                        int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, CCONSTR));
                        if (iCnt == 0)
                        {
                            string cFilter = string.Format(" where a.poid='{0}'", iPoid);
                            int id = 0;
                            string cCode = "";
                            string cInterLx = "采购订单INS销售中间表";
                            string cRe = XT.VoucherINSZJB(cInterLx, cFilter, XT.cConStrA, out id, out cCode);
                            //if (cRe != "ok")
                            //{
                                cErr += cInterLx + ":" + cPoid + "，" + cRe + "\r\n";
                            //}
                            //else
                            {
                                //协同定义的客户信息
                                sqlpo = string.Format("Update zdy_inter_somain set ccuscode='{0}',ccusname ='{1}',CCUSOADDRESS='{2}' where id = '{3}'",
                                    XT.GetcCusCode(), XT.GetcCusName(), XT.GetcCusAddress(), id);
                                DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);

                            }

                            WriteInterLog(iPoid, cPoid, id.ToString(), CLX, cInterLx, cRe,CCONSTR);
                        }
                    }
                    //查询单据然后批量进行更新
                    sqlpo = string.Format(@"SELECT id,cpoid,poid  FROM zdy_inter_somain WHERE  cstatus ='0' ");

                    DataTable dt = DbHelper2.Execute(sqlpo, CCONSTR).Tables[0];
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        int iInterid = DbHelper.GetDbInt(dt.Rows[k]["id"]);
                        string cPoid = DbHelper.GetDbString(dt.Rows[k]["cpoid"]);
                        int iPoid = DbHelper.GetDbInt(dt.Rows[k]["poid"]);

                        //查询目标库里有没有
                        sqlpo = string.Format("select count(1) from so_somain_extradefine  where  {0}='{1}'", XT.cSourceCodeColB, "数字采购订单-" + cPoid);
                        int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, XT.cConStrB));
                        if (iCnt > 0)
                        {

                            cErr += cPoid + "已有协同单据，请检查！" + "\r\n";

                        }
                        else
                        {
                            //新增插入目标表
                            //string cFilter = string.Format(" where a.id='{0}'", iInterid);
                            int id = 0;
                            string cCode = "";
                            string cInterLx = "销售中间表TO销售订单";
                            string cRe = XT.ZJBToVoucher(cInterLx, iInterid, XT.cConStrB, out id, out cCode);

                            if (cRe == "ok")
                            {
                                sqlpo = string.Format("Update zdy_inter_somain set cstatus='1',dupdatetime= getdate(),cremark='{0}' where id = '{1}'", cCode, iInterid);
                                DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);

                                //发送消息，1 A账的采购订单 2 B账的销售订单
                                 FaSongXiaoxi.FaSong("销售订单", id, string.Format("数字采购订单{0}协同生成一张新的销售订单{1}", cPoid, cCode), XT.cZTB, XT.iYearB, "demo", CCONSTR);


                                //回写原单据信息
                                sqlpo = string.Format("Update po_pomain_extradefine set {0}='{1}' where poid = '{2}'", XT.cTargetCodeColA, "激光销售订单-" + cCode, iPoid);
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);

                                FaSongXiaoxi.FaSong("采购订单",iPoid,string.Format("采购订单{0}协同生成一张新的激光销售订单{1}",cPoid,cCode),XT.cZTA,XT.iYearA,"demo",CCONSTR);
                            }
                            else
                            {
                                FaSongXiaoxi.FaSong("采购订单", iPoid, string.Format("注意： 采购订单{0}协同生成销售订单失败：{1}", cPoid,cRe), XT.cZTA, XT.iYearA, "demo", CCONSTR);
                            }
                            cErr += cInterLx + ":" + cPoid + "，" + cRe + "\r\n";
                            WriteInterLog(iInterid, cPoid, cCode, CLX, cInterLx, cRe,CCONSTR);
                        }
                    }
                    #endregion
                    break;
                case "数字发货单转激光发货单":
                    #region A发货单到B发货单
                    //查询单据然后批量进行更新,  发货单.   来源采购订单号不能为空，为空的不传。
                    sqlpo = string.Format(@"SELECT distinct  a.cdlcode ,a.dlid FROM dispatchlist a,dbo.dispatchlist_extradefine b,dispatchlists c WHERE a.dlid= b.dlid and a.dlid = c.dlid and 
c.cwhcode ='{0}' and isnull(cVerifier,'')<>'' 
 and isnull(c.cdefine23,'')<>''   ",  XT.GetcWhcode());

                    //有id的取id，没id的取最近一个月的
                    if (IID != 0)
                    {
                        sqlpo += string.Format(" and a.dlid= {0}", IID);
                    }
                    else
                    {
                        sqlpo += String.Format(" and isnull({0},'')='' and a.ddate>'2021-9-8' and a.ddate>DATEADD(MONTH,-1,getdate())", XT.cTargetCodeColA);
                    }

                    dtSource = DbHelper2.Execute(sqlpo, XT.cConStrA).Tables[0];
                    for (int k = 0; k < dtSource.Rows.Count; k++)
                    {
                        int iSourceId = DbHelper.GetDbInt(dtSource.Rows[k]["dlid"]);
                        string cSourceCode = DbHelper.GetDbString(dtSource.Rows[k]["cdlcode"]);
                        sqlpo = string.Format(@"select count(0) from ZDY_INTER_DISPATCHLIST where (cstatus ='0') and dlid = '{0}'  ", iSourceId);
                        int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, CCONSTR));
                        if (iCnt == 0)
                        {

                            string cFilter = string.Format(" where a.dlid='{0}' and   isnull(b.cdefine23,'')<>''  ", iSourceId);
                            int id = 0;
                            string cCode = "";
                            string cInterLx = "发货单INS发货中间表";
                            string cRe = XT.VoucherINSZJB(cInterLx, cFilter, XT.cConStrA, out id, out cCode);
                            if (cRe != "ok")
                            {
                                cErr += cInterLx + ":" + cSourceCode + "，" + cRe + "\r\n";
                            }
                            else
                            {
                                //cSOCode,isosid

                                //根据表体的cdefine2,采购入库单查询采购订单的子表id ，用这个标识icoridlsid

                                sqlpo = string.Format(@"UPDATE a  SET icoridlsid=c.id  FROM INTER_DATA..ZDY_INTER_DISPATCHLISTS a,dbo.PO_Pomain b ,dbo.PO_Podetails c
WHERE a.id  ={0} and b.poid = c.poid  AND a.cDefine23 = b.cPOID   AND a.cInvCode = c.cInvCode", id);
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);
                                //根据采购订单的id，查询关联生成的销售id
                                sqlpo = string.Format(@"UPDATE a SET a.iSOsID = b.iSOsID FROM INTER_DATA..ZDY_INTER_DISPATCHLISTS a ,dbo.SO_SODetails  b
WHERE  a.id  ={0} AND a.icoridlsid=b.{1}", id, XT.GetSourceColsB());
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);
                                //检查是否还有isosid未关联上的
                                sqlpo = string.Format(@"Select count(0) from ZDY_INTER_DISPATCHLISTS where id= {0} and  isnull(isosid,0)=0", id);
                                int iCntdisp = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, CCONSTR));
                                if (iCntdisp > 0)
                                {
                                    cErr += cInterLx + ":" + cSourceCode + "，不能关联激光的销售订单，请检查！ " + "\r\n";
                                    sqlpo = string.Format(@"update ZDY_INTER_DISPATCHLIST set cstatus='98' where id= {0}", id);
                                    DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);
                                    continue;
                                }
                                else
                                {
                                    //协同定义的客户信息,找字段写进去，还有对应的销售订单子表id
                                    sqlpo = string.Format(@"UPDATE c SET c.cCusCode = d.cCusCode,c.cCusName=d.cCusName,c.cDepCode=d.cDepCode,
c.iExchRate=d.iExchRate,c.cexch_name=d.cexch_name FROM INTER_DATA..ZDY_INTER_DISPATCHLISTS a ,dbo.SO_SODetails  b,
INTER_DATA..ZDY_INTER_DISPATCHLIST c,dbo.SO_SOMain d 
WHERE a.id =c.id AND b.id= d.ID AND 
a.iSOsID = b.iSOsID and a.id = {0}", id);
                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);
                                    //单价更新
                                    sqlpo = string.Format(@"UPDATE a SET  a.iQuotedPrice=b.iQuotedPrice,a.iUnitPrice=b.iUnitPrice,a.iTaxUnitPrice=b.iTaxUnitPrice,
a.iNatUnitPrice=b.iNatUnitPrice,a.isum = ROUND(b.iTaxUnitPrice*a.iQuantity,2),a.iNatSum= ROUND(b.iTaxUnitPrice*a.iQuantity,2),
a.iTaxRate =b.iTaxRate,a.csocode = b.csocode FROM INTER_DATA..ZDY_INTER_DISPATCHLISTS a ,dbo.SO_SODetails  b
WHERE a.iSOsID = b.iSOsID AND a.id = {0}", id);
                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);

                                    sqlpo = string.Format(@"UPDATE a SET a.iMoney =ROUND(a.isum*100/(100+a.iTaxRate),2),a.iNatMoney = ROUND(a.isum*100/(100+a.iTaxRate),2),
itax = isum-ROUND(a.isum*100/(100+a.iTaxRate),2),a.iNatTax= isum-ROUND(a.isum*100/(100+a.iTaxRate),2) FROM INTER_DATA..ZDY_INTER_DISPATCHLISTS a 
WHERE  a.id = {0}", id);
                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);
                                }

                            }

                            WriteInterLog(iSourceId, cSourceCode, id.ToString(), CLX, cInterLx, cRe,CCONSTR);
                        }

                    }
                    //查询单据然后批量进行更新。。
                    sqlpo = string.Format(@"SELECT id,cdlcode,dlid  FROM ZDY_INTER_DISPATCHLIST WHERE  cstatus ='0' ");
                    dtInter = DbHelper2.Execute(sqlpo, CCONSTR).Tables[0];
                    for (int k = 0; k < dtInter.Rows.Count; k++)
                    {
                        int iInterid = DbHelper.GetDbInt(dtInter.Rows[k]["id"]);
                        string cSourceCode = DbHelper.GetDbString(dtInter.Rows[k]["cdlcode"]);
                        int iSourceId = DbHelper.GetDbInt(dtInter.Rows[k]["dlid"]);

                        //查询目标库里有没有
                        sqlpo = string.Format("select count(1) from DISPATCHLIST_extradefine  where  {0}='{1}'", XT.cSourceCodeColB, "数字发货单-" + cSourceCode);
                        int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, XT.cConStrB));
                        if (iCnt > 0)
                        {

                            cErr += cSourceCode + "已有协同单据，请检查！" + "\r\n";

                        }
                        else
                        {
                            //新增插入目标表
                            //string cFilter = string.Format(" where a.id='{0}'", iInterid);
                            int id = 0;
                            string cCode = "";
                            string cInterLx = "发货中间表TO发货单";
                            string cRe = XT.ZJBToVoucher(cInterLx, iInterid, XT.cConStrB, out id, out cCode);

                            if (cRe == "ok")
                            {
                                sqlpo = string.Format("Update zdy_inter_dispatchlist set cstatus='1',dupdatetime= getdate(),cremark='{0}' where id = '{1}'", cCode, iInterid);
                                DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);
                                //激光消息提示
                                FaSongXiaoxi.FaSong("发货单", id, string.Format("数字发货单{0}协同生成一张新的发货单{1}", cSourceCode, cCode), XT.cZTB, XT.iYearB, "demo", CCONSTR);


                                //回写原单据信息
                                sqlpo = string.Format("Update DISPATCHLIST_extradefine set {0}='{1}' where dlid = '{2}'", XT.cTargetCodeColA, "激光发货单-" + cCode, iSourceId);
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);

                                //数字消息提示
                                FaSongXiaoxi.FaSong("发货单", iSourceId, string.Format("发货单{0}协同生成一张新的激光发货单{1}", cSourceCode, cCode), XT.cZTA, XT.iYearA, "demo", CCONSTR);

                            }
                            else
                            {
                                cErr += cInterLx + ":" + iSourceId + "，" + cRe + "\r\n";
                                FaSongXiaoxi.FaSong("发货单", iSourceId, string.Format("注意： 发货单{0}协同生成激光发货单失败", cSourceCode), XT.cZTA, XT.iYearA, "demo", CCONSTR);
                            }
                            WriteInterLog(iInterid, cSourceCode, cCode, CLX, cInterLx, cRe,CCONSTR);
                        }
                    }
                    #endregion
                    break;
                case "激光出库单转数字采购入库单":
                    #region B销售出库单到A采购入库单

                    ////删除中间表冗余信息
                    //sqlpo = @"delete from b from  ZDY_INTER_rdrecord01 a,ZDY_INTER_rdrecords01 b 
                    //    where a.id =b.id and a.cstatus = 98";
                    //DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);
                    //sqlpo = "delete from ZDY_INTER_rdrecord01 where cstatus = 98";
                    //DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);

                    //查询单据然后批量进行更新,  发货单.   来源采购订单号不能为空，为空的不传。
                    sqlpo = string.Format(@"SELECT distinct  a.id,a.ccode FROM rdrecord32 a,dbo.rdrecord32_extradefine b WHERE a.id= b.id
and a.ccuscode ='{0}' and isnull(chandler,'')<>'' 
 ", XT.GetcCusCode());

                    //有id的取id，没id的取最近一个月的
                    if (IID != 0)
                    {
                        sqlpo += string.Format(" and a.id= {0}", IID);
                    }
                    else
                    {
                        sqlpo += String.Format(" and isnull({0},'')=''  and a.ddate>'2021-9-8' and a.ddate>DATEADD(MONTH,-1,getdate())", XT.cTargetCodeColB);
                    }

                    dtSource = DbHelper2.Execute(sqlpo, XT.cConStrB).Tables[0];
                    for (int k = 0; k < dtSource.Rows.Count; k++)
                    {
                        //销售出库单id和单据号
                        int iSourceId = DbHelper.GetDbInt(dtSource.Rows[k]["id"]);
                        string cSourceCode = DbHelper.GetDbString(dtSource.Rows[k]["ccode"]);
                        sqlpo = string.Format(@"select count(0) from ZDY_INTER_rdrecord01 where (cstatus ='0' ) and rdid = '{0}'  ", iSourceId);
                        int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, CCONSTR));
                        if (iCnt == 0)
                        {

                            string cFilter = string.Format(" where a.id='{0}' ", iSourceId);
                            int id = 0;
                            string cCode = "";
                            string cInterLx = "销售出库单INS采购入库中间表";
                            string cRe = XT.VoucherINSZJB(cInterLx, cFilter, XT.cConStrB, out id, out cCode);
                            if (cRe != "ok")
                            {
                                cErr += cInterLx + ":" + cSourceCode + "，" + cRe + "\r\n";
                            }
                            else
                            {
                                //cSOCode,isosid

                                //idlsid ,isosid ,找到源头销售订单的自定义项14,来源采购订单的id

                                sqlpo = string.Format(@"UPDATE a  SET {1}=c.{1}  FROM INTER_DATA..ZDY_INTER_rdrecords01 a,dispatchlists b,dbo.sO_sodetails c
WHERE a.id  ={0}  and a.iOriTrackID=b.idlsid and b.isosid = c.isosid", id, XT.GetSourceColsB());
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);
                                //根据采购订单的id，查询关联生成的销售id
                                sqlpo = string.Format(@"UPDATE a SET a.iposid = b.id FROM INTER_DATA..ZDY_INTER_rdrecords01 a ,dbo.po_pODetails  b
WHERE  a.id  ={0} AND a.{1}=b.id", id, XT.GetSourceColsB());
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);
                                //检查是否还有isosid未关联上的
                                sqlpo = string.Format(@"Select count(0) from ZDY_INTER_rdrecords01 where id= {0} and  isnull(iposid,0)=0", id);
                                int iCntdisp = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, CCONSTR));
                                if (iCntdisp > 0)
                                {
                                    cErr += cInterLx + ":" + cSourceCode + "，不能关联数字的采购订单，请检查！ " + "\r\n";
                                    sqlpo = string.Format(@"update ZDY_INTER_rdrecord01 set cstatus='98' where id= {0}", id);
                                    DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);

                                    //回写原单据信息
                                    sqlpo = string.Format("Update rdrecord32_extradefine set {0}='不能关联数字的采购订单' where id = '{1}'", XT.cTargetCodeColB,  iSourceId);
                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);
                                    continue;
                                }
                                else
                                {
                                    //更新入库仓库
                                    sqlpo = string.Format(@"UPDATE a SET cwhcode = '{1}'  FROM INTER_DATA..ZDY_INTER_rdrecord01 a
WHERE a.id = {0}", id, XT.GetcWhcode());
                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);
                                    //                                              
                                    //更新是否协同产生的发货单  生成的 出库单
                                    //查询采购入库单的来源，是否是来源数字的发货单 ,写作表体自定义项13
                                    sqlpo = string.Format(@"update  f set cdefine34= c.{2}   FROM rdrecord32 a
inner join rdrecords32 b on a.id = b.id 
inner join dispatchlists c on b.idlsid = c.idlsid
inner join dispatchlist_extradefine d  on c.dlid = d.dlid 
inner join INTER_DATA..ZDY_INTER_rdrecords01 f on b.autoid = f.rdsid 
 where d.{0} like '数字发货单%' and a.id = {1}  and f.id ={3}", XT.cSourceCodeColB, iSourceId, XT.GetSourceColsB(), id);

                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);

                                    //无协同的更改成成品库
                                    sqlpo = string.Format(@"update  a set cwhcode= '0001'   FROM 
INTER_DATA..ZDY_INTER_rdrecord01 a
inner join INTER_DATA..ZDY_INTER_rdrecords01 b on a.id = b.id 
 where a.id = {0}  and isnull(b.cdefine34,'')=''  ", id);
                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);



                                }

                            }

                            WriteInterLog(iSourceId, cSourceCode, id.ToString(), CLX, cInterLx, cRe,CCONSTR);
                        }

                    }
                    //查询单据然后批量进行更新。。
                    sqlpo = string.Format(@"SELECT id,ccode,rdid  FROM ZDY_INTER_rdrecord01 WHERE  cstatus ='0' ");
                    dtInter = DbHelper2.Execute(sqlpo, CCONSTR).Tables[0];
                    for (int k = 0; k < dtInter.Rows.Count; k++)
                    {
                        int iInterid = DbHelper.GetDbInt(dtInter.Rows[k]["id"]);
                        string cSourceCode = DbHelper.GetDbString(dtInter.Rows[k]["ccode"]);
                        int iSourceId = DbHelper.GetDbInt(dtInter.Rows[k]["rdid"]);

                        //查询目标库里有没有
                        sqlpo = string.Format("select count(1) from rdrecord01_extradefine  where  {0}='{1}'", XT.cSourceCodeColA, "激光销售出库单-" + cSourceCode);
                        int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, XT.cConStrA));
                        if (iCnt > 0)
                        {

                            cErr += cSourceCode + "已有协同单据，请检查！" + "\r\n";

                        }
                        else
                        {
                            //新增插入目标表
                            //string cFilter = string.Format(" where a.id='{0}'", iInterid);
                            int id = 0;
                            string cCode = "";
                            string cInterLx = "采购入库中间表TO采购入库单";
                            string cRe = XT.ZJBToVoucher(cInterLx, iInterid, XT.cConStrA, out id, out cCode);

                            if (cRe == "ok")
                            {
                                sqlpo = string.Format("Update zdy_inter_rdrecord01 set cstatus='1',dupdatetime= getdate(),cremark='{0}' where id = '{1}'", cCode, iInterid);
                                DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);

                                //数字采购入库单
                                FaSongXiaoxi.FaSong("采购入库单", id, string.Format("激光销售出库单{0}协同生成一张新的采购入库单{1}", cSourceCode, cCode), XT.cZTA, XT.iYearA, "demo", CCONSTR);

                                //回写原单据信息
                                sqlpo = string.Format("Update rdrecord32_extradefine set {0}='{1}' where id = '{2}'", XT.cTargetCodeColB, "数字采购入库单-" + cCode, iSourceId);
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);

                                //激光销售出库单
                                FaSongXiaoxi.FaSong("销售出库单", iSourceId, string.Format("销售出库单{0}协同生成一张新的数字采购入库单{1}", cSourceCode, cCode), XT.cZTB, XT.iYearB, "demo", CCONSTR);


                                WriteInterLog(iSourceId, cSourceCode, id.ToString(), CLX, cInterLx, cRe,CCONSTR);
                                #region A采购入库单到A销售出库单
                                //查询采购入库单的来源，是否是来源数字的发货单
                                sqlpo = string.Format(@" select distinct a.id from rdrecord01 a,rdrecords01 b where a.id = b.id and isnull(b.cdefine34,0)<>0 and a.id = {0} ", id);

                                int iRDid = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, XT.cConStrA));
                                if (iRDid != 0)
                                {
                                    //是发货单协同生成的


                                    string cFilter = string.Format(" where a.id='{0}' ", iRDid);
                                    int id2 = 0;
                                    string cCode2 = "";
                                    cInterLx = "采购入库单TO销售出库单";
                                    cRe = XT.VoucherToVoucher(cInterLx, iRDid, cFilter, XT.cConStrA, out id2, out cCode2);
                                    if (cRe != "ok")
                                    {
                                        cErr += cInterLx + ":" + cSourceCode + "，" + cRe + "\r\n";
                                    }
                                    else
                                    {
                                        sqlpo = string.Format(@"UPDATE a  SET {0}='{1}'  FROM rdrecord01_extradefine  a
WHERE a.id  ={2} ", XT.cTargetCodeColA, "数字销售出库单-" + cCode2, iRDid);
                                        DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);

                                        sqlpo = string.Format(@"UPDATE a  SET {0}='{1}'  FROM rdrecord32_extradefine  a
WHERE a.id  ={2} ", XT.cSourceCodeColA, "数字采购入库单-" + cCode, id2);
                                        DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);

                                        //数字采购入库单
                                        FaSongXiaoxi.FaSong("采购入库单", id2, string.Format("协同生成采购入库单{0}，再次协同生成一张最终客户销售出库单{1}", cCode, cCode2), XT.cZTA, XT.iYearB, "demo", CCONSTR);

                                    }

                                    WriteInterLog(iSourceId, cSourceCode, id.ToString(), CLX, cInterLx, cRe, CCONSTR);
                                }
                                else
                                {
                                    sqlpo = string.Format(@"UPDATE a  SET {0}='{1}'  FROM rdrecord01_extradefine  a
WHERE a.id  ={2} ", XT.cTargetCodeColA, "非客户发货，不协同生成采购入库", iRDid);
                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);

                                }
                                #endregion

                            }
                            else
                            {
                                cErr += cInterLx + ":" + cSourceCode + "，" + cRe + "\r\n";
                                WriteInterLog(iSourceId, cSourceCode, id.ToString(), CLX, cInterLx, cRe,CCONSTR);

                            }



                        }
                    }
                    #endregion


                    break;
                case "激光销售发票转数字采购发票":
                    #region B销售发票到A采购发票

                    //查询单据然后批量进行更新,  发货单.   来源采购订单号不能为空，为空的不传。
                    sqlpo = string.Format(@"SELECT distinct  a.sbvid,a.csbvcode FROM salebillvouch a,dbo.salebillvouch_extradefine b WHERE a.sbvid= b.sbvid
and a.ccuscode ='{0}'   and isnull(cChecker,'')<>'' 
 ", XT.GetcCusCode());
                    //有id的取id，没id的取最近一个月的
                    if (IID != 0)
                    {
                        sqlpo += string.Format(" and a.sbvid= {0}", IID);
                    }
                    else
                    {
                        sqlpo += String.Format(" and isnull({0},'')='' and a.ddate>'2021-9-8' and a.ddate>DATEADD(MONTH,-1,getdate())", XT.cTargetCodeColB);
                    }


                    dtSource = DbHelper2.Execute(sqlpo, XT.cConStrB).Tables[0];
                    for (int k = 0; k < dtSource.Rows.Count; k++)
                    {
                        int iSourceId = DbHelper.GetDbInt(dtSource.Rows[k]["sbvid"]);
                        string cSourceCode = DbHelper.GetDbString(dtSource.Rows[k]["csbvcode"]);
                        sqlpo = string.Format(@"select count(0) from ZDY_INTER_PURBILLVOUCH where (cstatus ='0' ) and pbvid = '{0}'  ", iSourceId);
                        int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, CCONSTR));
                        if (iCnt == 0)
                        {

                            string cFilter = string.Format(" where a.sbvid='{0}' ", iSourceId);
                            int id = 0;
                            string cCode = "";
                            string cInterLx = "销售发票INS采购发票中间表";
                            string cRe = XT.VoucherINSZJB(cInterLx, cFilter, XT.cConStrB, out id, out cCode);
                            if (cRe != "ok")
                            {
                                cErr += cInterLx + ":" + cSourceCode + "，" + cRe + "\r\n";
                            }
                            else
                            {

                                //idlsid ,isosid ,根据来源的idlisid，找B账的采购入库的cdefine35，的autoid,
                                //使用isbsid

                                //                                             sqlpo = string.Format(@"UPDATE a  SET cDefine35=c.{1}  FROM INTER_DATA..ZDY_INTER_PURBILLVOUCHS a,rdrecords32 b
                                //WHERE a.id  ={0}  and a.iSBsID=b.autoid  ", id, CanShu.cSourceColsB);
                                //                                             DbHelper2.ExecuteNonQuery(sqlpo, CanShu.cConStrB);
                                //根据采购订单的id，查询关联生成的销售id
                                sqlpo = string.Format(@"UPDATE a SET a.rdsid = b.autoid FROM INTER_DATA..ZDY_INTER_PURBILLVOUCHS a ,dbo.rdrecords01  b
WHERE  a.id  ={0} AND b.{1}=a.iSBsID", id, XT.GetSourceColsA());
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);
                                //检查是否还有isosid未关联上的
                                sqlpo = string.Format(@"Select count(0) from ZDY_INTER_PURBILLVOUCHS where id= {0} and  isnull(rdsid,0)=0", id);
                                int iCntdisp = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, CCONSTR));
                                if (iCntdisp > 0)
                                {
                                    cErr += cInterLx + ":" + cSourceCode + "，不能关联数字的采购入库单，请检查！ " + "\r\n";

                                    sqlpo = string.Format(@"update ZDY_INTER_PURBILLVOUCH set cstatus='98' where id= {0}", id);
                                    DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);

                                    //回写原单据信息
                                    sqlpo = string.Format("Update salebillvouch_extradefine set {0}='不能关联数字的采购入库单' where sbvid = '{1}'", XT.cTargetCodeColB, iSourceId);
                                    DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);


                                    continue;
                                }


                            }

                            WriteInterLog(iSourceId, cSourceCode, id.ToString(), CLX, cInterLx, cRe,CCONSTR);
                        }

                    }
                    //查询单据然后批量进行更新。。
                    sqlpo = string.Format(@"SELECT id,cpbvcode,pbvid  FROM ZDY_INTER_PURBILLVOUCH WHERE  cstatus ='0' ");
                    dtInter = DbHelper2.Execute(sqlpo, CCONSTR).Tables[0];
                    for (int k = 0; k < dtInter.Rows.Count; k++)
                    {
                        int iInterid = DbHelper.GetDbInt(dtInter.Rows[k]["id"]);
                        string cSourceCode = DbHelper.GetDbString(dtInter.Rows[k]["cpbvcode"]);
                        int iSourceId = DbHelper.GetDbInt(dtInter.Rows[k]["pbvid"]);

                        //查询目标库里有没有
                        sqlpo = string.Format("select count(1) from PURBILLVOUCH_extradefine  where  {0}='{1}'", XT.cSourceCodeColA, "销售发票(激光)-" + cSourceCode);
                        int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sqlpo, XT.cConStrA));
                        if (iCnt > 0)
                        {

                            cErr += cSourceCode + "已有协同单据，请检查！" + "\r\n";

                        }
                        else
                        {
                            //新增插入目标表
                            //string cFilter = string.Format(" where a.id='{0}'", iInterid);
                            int id = 0;
                            string cCode = "";
                            string cInterLx = "采购发票中间表TO采购发票";
                            string cRe = XT.ZJBToVoucher(cInterLx, iInterid, XT.cConStrA, out id, out cCode);

                            if (cRe == "ok")
                            {
                                sqlpo = string.Format("Update zdy_inter_PURBILLVOUCH set cstatus='1',dupdatetime= getdate(),cremark='{0}' where id = '{1}'", cCode, iInterid);
                                DbHelper2.ExecuteNonQuery(sqlpo, CCONSTR);
                                //数字采购发票
                                FaSongXiaoxi.FaSong("采购专用发票", id, string.Format("激光销售发票{0}协同生成一张新的采购发票{1}", cSourceCode, cCode), XT.cZTA, XT.iYearA, "demo", CCONSTR);
                                //回写原单据信息
                                sqlpo = string.Format("Update salebillvouch_extradefine set {0}='{1}' where sbvid = '{2}'", XT.cTargetCodeColB, "数字采购发票-" + cCode, iSourceId);
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrB);

                                //激光销售发票
                                FaSongXiaoxi.FaSong("销售专用发票", iSourceId, string.Format("销售发票{0}协同生成一张新的数字采购发票{1}", cSourceCode, cCode), XT.cZTB, XT.iYearB, "demo", CCONSTR);
                            }
                            else
                            {
                                cErr += cInterLx + ":" + cSourceCode + "，" + cRe + "\r\n";
                            }


                            WriteInterLog(iSourceId, cSourceCode, id.ToString(), CLX, cInterLx, cRe,CCONSTR);

                        }
                    }
                    #endregion


                    break;
                case "数字采购入库单转数字出库单":
                    #region A数字采购入库单到A出库单


                    //查询单据然后批量进行更新,  发货单.   来源采购订单号不能为空，为空的不传。
                    sqlpo = string.Format(@" 
SELECT distinct  a.id,a.ccode  FROM rdrecord01 a,dbo.rdrecord01_extradefine b WHERE a.id= b.id
and A.cWhCode ='{0}' and isnull(chandler,'')<>'' and isnull(chdefine4,'')<>''  ", XT.GetcWhcode() );


                    //有id的取id，没id的取最近一个月的
                    if (IID != 0)
                    {
                        sqlpo += string.Format(" and a.id= {0}", IID);
                    }
                    else
                    {
                        sqlpo += String.Format(" and isnull({0},'')=''  and a.ddate>'2021-9-8' and a.ddate>DATEADD(MONTH,-1,getdate())", XT.cTargetCodeColB);
                    }
                    dtSource = DbHelper2.Execute(sqlpo, XT.cConStrA).Tables[0];
                    for (int k = 0; k < dtSource.Rows.Count; k++)
                    {

                        #region A采购入库单到A销售出库单
                        //查询采购入库单的来源，是否是来源数字的发货单
                        int iRDid = DbHelper.GetDbInt(dtSource.Rows[k]["id"]);
                        string cSourceCode = DbHelper.GetDbString(dtSource.Rows[k]["ccode"]);
 
                        if (iRDid != 0)
                        {
                            //是发货单协同生成的
                            string cFilter = string.Format(" where a.id='{0}' ", iRDid);
                            int id2 = 0;
                            string cCode2 = "";
                            String   cInterLx = "采购入库单TO销售出库单";
                            String cRe = XT.VoucherToVoucher(cInterLx, iRDid, cFilter, XT.cConStrA, out id2, out cCode2);
                            if (cRe != "ok")
                            {
                                cErr += cInterLx + ":" + cSourceCode + "，" + cRe + "\r\n";
                                sqlpo = string.Format(@"UPDATE a  SET {0}='{1}'  FROM rdrecord01_extradefine  a
WHERE a.id  ={2} ", XT.cTargetCodeColA, cRe, iRDid);
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);
                            }
                            else
                            {
                                sqlpo = string.Format(@"UPDATE a  SET {0}='{1}'  FROM rdrecord01_extradefine  a
WHERE a.id  ={2} ", XT.cTargetCodeColA, "数字销售出库单-" + cCode2, iRDid);
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);

                                sqlpo = string.Format(@"UPDATE a  SET {0}='{1}'  FROM rdrecord32_extradefine  a
WHERE a.id  ={2} ", XT.cSourceCodeColA, "数字采购入库单-" + cSourceCode, id2);
                                DbHelper2.ExecuteNonQuery(sqlpo, XT.cConStrA);

                                //数字采购入库单
                                FaSongXiaoxi.FaSong("采购入库单", id2, string.Format("采购入库单{0}协同生成一张最终客户销售出库单{1}", cSourceCode, cCode2), XT.cZTA, XT.iYearB, "demo", CCONSTR);

                            }

                            WriteInterLog(iRDid, cSourceCode, cCode2.ToString(), CLX, cInterLx, cRe, CCONSTR);
                        }
                         
                        #endregion
                        //else
                        //{
                        //    cErr += cInterLx + ":" + cSourceCode + "，" + cRe + "\r\n";
                        //    WriteInterLog(iSourceId, cSourceCode, id.ToString(), CLX, cInterLx, cRe, CCONSTR);

                        //}
                    }
                          



                     
                    #endregion


                    break;
                   
                 case "all":
                    #region 所有的执行
                    cErr += HANDSMLXieTong("存货档案同步", 0, CCONSTR)+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+ "\r\n";
                    cErr += HANDSMLXieTong("客户档案同步", 0, CCONSTR) + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";
                    cErr += HANDSMLXieTong("数字采购订单转激光销售订单", 0, CCONSTR) + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";
                    cErr += HANDSMLXieTong("数字发货单转激光发货单", 0, CCONSTR) + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";
                    cErr += HANDSMLXieTong("激光出库单转数字采购入库单", 0, CCONSTR) + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";
                    cErr += HANDSMLXieTong("激光销售发票转数字采购发票", 0, CCONSTR) + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";
                    cErr += HANDSMLXieTong("数字采购入库单转数字出库单", 0, CCONSTR) + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";
                    #endregion


                    break;
                default:
                    break;
            }


            return cErr;
        }

        /// <summary>
        /// 单据变更业务同步，使用临时表，不使用中间表
        /// 中间表，仅作为提供字段的作用
        /// </summary>
        /// <param name="CLX">同步类型</param>
        /// <param name="IID">同步id </param>
        /// <param name="CCONSTR">中间库连接字符串</param>
        /// <returns></returns>
        public string UpdateSMLXieTong(string CLX, int IID, string CCONSTR)
        {
            string cErr = "";
            string sqlpo = "";
            DataTable dtSource = new DataTable();
            DataTable dtInter = new DataTable();
            XieTong XT = new XieTong(CCONSTR);
            TongBu tongBu = new TongBu(CCONSTR, 1);

            if (IID == 0)
            {
                return "未指定单据号";
            }
            switch (CLX)
            {
                case "数字采购订单转激光销售订单":
                    #region  A采购订单到B销售订单
                    //查询单据然后批量进行更新
                    cErr = "";
                    sqlpo += string.Format(" and a.poid= {0}", IID);
                    string cRe = XT.UpdateVouch("采购订单INS销售中间表", sqlpo);
                    cErr = cRe;
                    WriteInterLog(IID, "", "", CLX, "数字采购订单转激光销售订单变更", cRe, CCONSTR);
                       
                    
                   
                    #endregion
                    break;
              
                default:
                    break;
            }


            return cErr;
        }

        #region 写入中间表日志


        private void WriteInterLog(int iSourceID, string cCode, string cTarCode, string cLx, string cInterLx, string cRe, string cConstr)
        {
            SqlParameter[] param = new SqlParameter[]{ 
                new SqlParameter("@ccode",cCode),
                new SqlParameter("@iSourceID",iSourceID),
                new SqlParameter("@cTarCode",cTarCode),
                 new SqlParameter("@cLx",cInterLx),
                new SqlParameter("@cInterLx",cInterLx),
                new SqlParameter("@cRe",cRe)                                         
          };
            string sql = string.Format(@"INSERT INTO ZDY_INTER_XIETONGLOG(ccode,ISOURCEID,CTARCODE,CLX,CINTERLX,DUPDATETIME,CREMARK)
VALUES(@ccode,@iSourceID,@cTarCode,@cLx,@cInterLx,getdate(),@cRe)");
            DbHelper2.ExecuteNonQuery(sql, param, CommandType.Text,cConstr);

        }
        #endregion
    }
}
